package com.eloo.otsclient.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;


public class FileUtil {
	 
	public  static List<File> getURLFile(String path) {
		List<File> filespath = new ArrayList<File>();
		File file = new File(path);
		File[] ff = file.listFiles();
		for (int i = 0; i < ff.length; i++) {
			File f = ff[i];
			List<File>  list = new ArrayList<File> ();
			if (f.isFile()) {
				if(f.getName().toLowerCase().endsWith("url"))
				filespath.add(f);
			} else if (f.isDirectory()) {
				list= getURLFile(f.getAbsolutePath());
			}
			filespath.addAll(list);
		} 
		return filespath;
	}
	public  static List<File> findFile(String path,String filename) {
		List<File> filespath = new ArrayList<File>();
		File file = new File(path);
		File[] ff = file.listFiles();
		for (int i = 0; i < ff.length; i++) {	File f = ff[i];
			List<File> list = new ArrayList<File>();
			if (f.isFile()) {
				if (f.getName().toLowerCase().equals(filename.toLowerCase()))
					filespath.add(f);
			} else if (f.isDirectory()) {
				list = findFile(f.getAbsolutePath(),filename);
			}
			filespath.addAll(list);
		}
		return filespath;
	}
	public  static List<File> findFolder(String path,String filename) {
		List<File> filespath = new ArrayList<File>();
		File file = new File(path);
		File[] ff = file.listFiles();
		for (int i = 0; i < ff.length; i++) {	File f = ff[i];
			List<File> list = new ArrayList<File>();
			if (f.isFile()) {
				continue;
			} else if (f.isDirectory()) {
				if(f.getName().toLowerCase().equals(filename.toLowerCase())){
					filespath.add(f);
				}
				list = findFile(f.getAbsolutePath(),filename);
			}
			filespath.addAll(list);
		}
		return filespath;
	}
	
	public static StringBuffer readFile(String filePath){ 
		return readFile(filePath,"UTF-8");
	}
	public static StringBuffer readFile(String filePath,String encode){ 
		
		StringBuffer sb=new StringBuffer();
		File file=new File(filePath);
			if(file.isFile()){
			
				try { 
					FileInputStream fi=new FileInputStream(file);
					BufferedReader r = new BufferedReader(new InputStreamReader(fi, encode)); 
					String value;
					while(( value=r.readLine())!=null){  
					sb.append(value);
					sb.append("\n");
					}
					fi.close();
				} catch (Exception e) {
				   new Exception("read "+file.getName()+" file error!");
				} 
			}
			return sb; 
	}
	
	
	
public static StringBuffer readFile(InputStream filecontent){ 
		
		StringBuffer sb=new StringBuffer();
		 
		 
 
				try { 
					ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
					byte[]  read=new byte[2];
					while((filecontent.read(read ))>-1){ 
						outSteam.write(read); 
						
					} 
					
				/*	byte[]	old=outSteam.toByteArray();
					for(int i=0;i<old.length,i++){
					
					}
					*/
					sb.append(outSteam.toString());
				 
				} catch (Exception e) {
				   new Exception("read  error!");
				} 
		 
			return sb; 
	}
	
	public static void convert(String infile, String outfile, String fromencode,
			String toencode) throws IOException, UnsupportedEncodingException {

		InputStream in;
		if (infile != null)
			in = new FileInputStream(infile);
		else
			in = System.in;
		OutputStream out;
		if (outfile != null)
			out = new FileOutputStream(outfile);
		else
			out = System.out;

		if (fromencode == null)
			fromencode = System.getProperty("file.encoding");
		if (toencode == null)
			toencode = System.getProperty("file.encoding");

		Reader r = new BufferedReader(new InputStreamReader(in, fromencode));
		Writer w = new BufferedWriter(new OutputStreamWriter(out, toencode));

		char[] buffer = new char[4096];
		int len;
		while ((len = r.read(buffer)) != -1)
			w.write(buffer, 0, len);
		 
		r.close();
		w.flush();
		w.close();
	}
	
public static InputStream getURLInputStream(String _url,String contenttype,String charset){
	InputStream is =null;
	try {
		URL url = new URL(_url);

		String hostName = url.getHost();
		int hostPort = url.getPort()<0?80:url.getPort();
		String hostPath = url.getPath();

		long startTime = System.currentTimeMillis();
		String info = " invoke, host: " + hostName + ", port: " + hostPort
				+ ", path: " + hostPath;

		// Create socket
		InetAddress addr = InetAddress.getByName(hostName);
		Socket socket = new Socket(addr, hostPort);

		// Send header
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		
		writer.write("GET " + hostPath + " HTTP/1.1\r\n");
		writer.write("Host: " + hostName + "\r\n");
		//writer.write("Content-Length: " + _url.length() + "\r\n");
		writer.write("Content-Type: "+contenttype+"; charset=\""+charset+"\"\r\n"); 
		writer.write("\r\n");

		// Send data
		writer.write(_url);
		writer.flush();

		// Response
		 is = socket.getInputStream(); 
 

	} catch (Exception e) {

	}  
	return is;
}



	public static String readURLString(String _url) {
		StringBuffer responseBuffer = new StringBuffer(); 
		BufferedReader reader = new BufferedReader(new InputStreamReader(getURLInputStream(_url,"text/html","utf-8")));

		// Skip HTTP header (terminated by an empty line)
		String line = null;
		try {
		do { 
			line = reader.readLine();
			
		} while (line != null && line.length() > 0);

		// Write remaining lines to response
		while ((line = reader.readLine()) != null) {
			responseBuffer.append(line + "\n");
		}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String response = responseBuffer.toString();

		return response;

	}

	 
	  public static void copyIcon(String _url,  String iconPath) {

	      // Read the icon from the jar file
	       
	      System.out.println(_url.lastIndexOf("/"));
	      File f = new File(iconPath + "\\" + _url.substring(_url.lastIndexOf('/'),_url.length()));

	      if (!f.getParentFile().exists()) {
	          f.getParentFile().mkdirs();
	      }

		// Write the icon to disk
	 
		InputStream in=getURLInputStream(_url,"image/x-icon","iso-8859-2");
		FileOutputStream bw;
		try {
			bw = new FileOutputStream(f); 
			int i=-1;
			while((i=in.read())!=-1){  
				if(i==012){  
					if((i=in.read())==13){  
						in.read();
					break;
					}
				}
			} 
			byte[] bytes=new byte[1024]; 
			while((i=in.read(bytes))!=-1){ 
				bw.write(bytes); 
				bytes=new byte[1024];
			}
			
			bw.flush();
			bw.close();
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
	  
	       
	    }
	public static  void writeIntoFile(String username, String pw) {
		File ftemp;
		StringBuffer sf = new StringBuffer(); 
		sf.append(username+"\n"+toLeft(pw));
	 	try {
	 		ftemp = new File(System.getProperty("java.io.tmpdir")+"netaccesspw.pw");  
			OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(ftemp, false), "UTF-8");
			ow.write(sf.toString());	
			ow.close();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
	
		}
		
	 public static String[] readFromFile(String encode) {
		 	String[] sb = new String[2]; 
		    File file = new File(System.getProperty("java.io.tmpdir")+"netaccesspw.pw");
		    if (file.isFile()) {
		      try
		      {
		        FileInputStream fi = new FileInputStream(file);
		        BufferedReader r = new BufferedReader(new InputStreamReader(fi, encode));
		        String value;
		        int line=0;
		        while ((value = r.readLine()) != null)
		        {
		          if (line == 0) {
		          sb[0] = value;
		          }
		          else if(line ==1){
		          sb[1] = toRight(value);  
		          }
		          line++;
		        
		        }
		        fi.close();
		      } catch (Exception e) {
		        new Exception("read " + file.getName() + " file error!");
		      }
		    }
		    return sb;
		  }

	 public static String toLeft(String str){
			StringBuffer newst = new StringBuffer(256);
			char chars[]= str.toCharArray();
			for(int i = 0;i < chars.length;i++){ 
				newst.append(String.format("%03d", (int)chars[i]^'S')); 
			} 
			return newst.toString();
		}
	 public static String toRight(String str){
			StringBuffer newst = new StringBuffer(256); 
			for(int i = 0; i< str.length()-1;i=i+3){ 
				String de=str.substring(i,i+3);  
				//System.out.println((char)(Integer.valueOf(de).intValue()<<1)); 
				newst.append((char)((Integer.valueOf(de).intValue()^'S'))); 
			} 
			return newst.toString();
		}
	
}
